from django.db import models

# Create your models here.
class Server(models.Model):
    '''
    服务器表
    '''
    hostname=models.CharField(max_length=32,verbose_name='主机名')

    def __str__(self):
        return self.hostname

    class Meta:
        verbose_name='服务器表'
        verbose_name_plural=verbose_name

class Project(models.Model):
    '''
    项目管理
    '''
    title=models.CharField(max_length=32,verbose_name='项目名')
    repo=models.CharField(max_length=128,verbose_name='仓库地址')
    env_choices=(('prod','正式环境'),('test','测试环境'))
    env=models.CharField(choices=env_choices,default='test',verbose_name='环境',max_length=32)
    server=models.ManyToManyField(to='Server',verbose_name='项目关联的服务器')
    path=models.CharField(max_length=128,verbose_name='线上项目地址',default='/data/prod/')

    class Meta:
        verbose_name='项目表'
        verbose_name_plural=verbose_name
    def __str__(self):
        return self.title


class DeployTask(models.Model):
    '''
    任务发布表
    '''
    uid=models.CharField(max_length=64,verbose_name='标识')
    project=models.ForeignKey(to='Project',on_delete=models.CASCADE,verbose_name='项目环境')
    tag=models.CharField(max_length=32,verbose_name='项目版本')
    status_choices=((1,'待发布'),(2,'发布中'),(3,'发布成功'),(4,'发布失败'))
    status=models.SmallIntegerField(choices=status_choices,default=1,verbose_name='任务状态')
    before_download_script=models.TextField(verbose_name='下载前脚本',null=True,blank=True)
    after_download_script=models.TextField(verbose_name='下载后脚本',null=True,blank=True)
    before_deploy_script = models.TextField(verbose_name='发布前脚本', null=True, blank=True)
    after_deploy_script = models.TextField(verbose_name='发布后脚本', null=True, blank=True)
    class Meta:
        verbose_name='任务发布表'
        verbose_name_plural=verbose_name
    def __str__(self):
        return self.uid


class HookTemplate(models.Model):
    '''
    钩子的模板
    '''
    title=models.CharField(max_length=32,verbose_name='标题')
    content=models.TextField(verbose_name='脚本内容')
    hook_type=((2,'下载前脚本'),(4,'下载后脚本'),(6,'发布前脚本'),(8,'发布后脚本'))
    hook=models.SmallIntegerField(choices=hook_type,verbose_name='脚本类型')

    def __str__(self):
        return self.title
    class Meta:
        verbose_name='钩子模板表'
        verbose_name_plural='钩子模板表'

class Node(models.Model):
    '''
    图表节点表
    '''
    text=models.CharField(max_length=32,verbose_name='节点名称')
    status_choices=(('lightgrey','待发布'),('green','成功'),('red','失败'),)
    status=models.CharField(verbose_name='状态',max_length=32,choices=status_choices,default='lightgrey')
    task=models.ForeignKey(to='DeployTask',on_delete=models.CASCADE,verbose_name='发布任务单')
    parent=models.ForeignKey(to='self',on_delete=models.CASCADE,verbose_name='父节点',null=True,blank=True)
    server=models.ForeignKey(to='Server',on_delete=models.CASCADE,verbose_name='服务器',null=True,blank=True)

    def __str__(self):
        return self.text
    class Meta:
        verbose_name='图表节点表'
        verbose_name_plural=verbose_name